import {forEach} from './util'
import { Vue } from './install'
class Store {
    constructor(options){
      const {state,mutations,modules,getters,actions} =options
      this.getters = {}
      this.mutations ={}
      this.actions = {} 
      const computed = {} 
    //   处理getters
      forEach(getters,(valFn,key)=>{
          computed[key]=()=>{
           return valFn(this.state)
          }
         Object.defineProperty(this.getters,key,{
             get:()=>this._vm[key]
         })
      })
    // 处理mutations
     forEach(mutations,(valFn,key)=>{
        this.mutations[key]=(payload)=>valFn.call(this,this.state, payload)
     })
     forEach(actions,(valFn,key)=>{
        this.actions[key]=(payload)=>valFn.call(this,this, payload)
     })
      this._vm = new Vue({
            data:{
                $$state:state
            },
            computed
        })

    }
    get state(){
        return this._vm._data.$$state
    }
    commit=(type,payload)=>{
        this.mutations[type](payload);
    }
    dispatch=(type,payload)=>{
        this.actions[type](payload)
    }
}

export default Store ; 